﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TbShop.Business.Components;
using TbShop.Entity;
using TbShop.Web.Areas.Admin.Models;
using TbShop.Web.Helpers;

namespace TbShop.Web.Areas.Admin.Controllers
{
    public class TbCategoryController : BaseCacheManageController<TbCategory, TbCategoryViewModel>
    {

        public TbCategoryController() : base("商品分类", "TbCategory", "TbCategory", true, true) { }
        public override ActionResult Index()
        {
            return base.Index();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public override ActionResult Edit(TbCategoryViewModel model)
        {
            //if (model.Id == 0)
            //{
            //    if (Request.Files == null || Request.Files["image"] == null || Request.Files["image"].ContentLength == 0)
            //    {
            //        SendMessage("主图不能为空", Constants.MessageType.Warning);
            //        return RedirectToAction("Edit", new { id = (model == null ? 0 : model.Id) });
            //    }
            //}
            if (Request.Files.Count > 0)
            {
                var file = this.Request.Files["image"];
                if (file != null && file.ContentLength > 0)
                    model.ImageUrl = ImageUrlHelper.SaveFileToUpload(file, StaticWords.UploadFolder.TbCategory);
            }
            var data = DataMapperHelper.Map<TbCategory>(model);
            data.FillEntity(User.Identity.Name);
            var saveResult = bc.Save(data);
            if (saveResult != null)
            {
                OperationLogHelper.SaveOperationLog(AdminId, (model.Id > 0 ? "修改" : "添加"), "分类", "", saveResult.Id.ToString());
                SendMessage("保存成功", Constants.MessageType.Success);
                CacheHelper<TbCategory>.ClearDates();
                return RedirectToAction("Index");
            }
            else
                SendMessage("保存失败", Constants.MessageType.Warning);
            return RedirectToAction("Edit", new { id = (saveResult == null ? 0 : saveResult.Id) });
        }

    }
}